package com.yimi.policyservice.service.impl;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import com.yimi.policyservice.common.constant.RedisConstant;
import com.yimi.policyservice.dto.code.ImageCode;
import com.yimi.policyservice.service.ImgCodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * @author jack
 */
@Service
public class ImgCodeServiceImpl implements ImgCodeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate ;



    @Override
    public ImageCode create() {
        String key = UUID.randomUUID().toString();
        LineCaptcha lineCaptcha = new LineCaptcha(116,40,4,10);
        stringRedisTemplate.opsForValue().set(String.format(RedisConstant.IMG_CODE_KEY,key),lineCaptcha.getCode(),10, TimeUnit.MINUTES);
        return new ImageCode(lineCaptcha.getImageBase64(),key);
    }

    @Override
    public boolean verify(String key, String code) {

        if(StringUtils.isBlank(code) || StringUtils.isBlank(key)){
            return  false ;
        }
        String cacheKey  = String.format(RedisConstant.IMG_CODE_KEY,key) ;
        String cacheCode = stringRedisTemplate.opsForValue().get(cacheKey);
        stringRedisTemplate.delete(cacheKey);
        return StringUtils.equals(code,cacheCode);
    }
}
